import { resolveYAML } from "@/utils/resolve-config-file";
import knex from "knex";
import path from "path";
import { insertSeedData } from "./seed-data";
import { create } from "./tables";

const dbConfig = resolveYAML(path.resolve(__dirname, "./db.yaml"));
const connection = {
    development: dbConfig.dev_db,
    production: dbConfig.prod_db,
    test: dbConfig.test_db
};

const db = knex({
    client: "mysql2",
    connection: () => connection[`${process.env.NODE_ENV}`],
    pool: { min: 2, max: 10 },
    debug: process.env.NODE_ENV === "development"
});

export default db;

// 创建表
export const createTables = async () => {
    try {
        await create();
        console.log("Tables created successfully");
    } catch (error) {
        console.log("error", error);
    }
};

// 重置表，清空数据，并插入种子数据
export const resetAndSeedTable = async () => {
    try {
        await insertSeedData();
        console.log("Reset and seed data inserted successfully");
    } catch (error) {
        console.log("error", error);
    }
};
